import type { IPoi, IPoiSearchResult } from "@/common/MapTypes";
import type { AMapCustomExposed } from "@/components/amapCustom/types";
import { ref, type Ref } from "vue";
import _ from "lodash-es";

export default function useSearch(
  amapRef: Ref<AMapCustomExposed | null>,
  poiList: IPoiSearchResult
) {
  const searchKeyRef = ref("");
  const searchPageNumber = ref(1);

  const popupFlexShowRef = ref(false);

  const handleSearch = _.debounce(async function handleSearch() {
    if (!searchKeyRef.value) return;

    // 移除地图上的之前搜索结果(marker)
    amapRef.value?.removeSearchMarker();
    uni.showLoading();
    const { status, result } = await amapRef.value!.localSearch(searchKeyRef, {
      pageIndex: searchPageNumber.value,
      pageSize: 10,
    });

    if (status === "complete") {
      uni.hideLoading();
      // 查询成功
      poiList.count = result?.poiList?.count;
      poiList.pois = result?.poiList?.pois;
      poiList.pois.map((item: IPoi) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        item.latitude = item.location.lat;
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        item.longitude = item.location.lng;
        item.extdata = {}; // 不能删除，因为 spacePanelItem 会用到
      });
    } else {
      // 查询失败
      uni.showToast({
        title: `查询错误,code：${status}`,
        icon: "none",
        mask: true,
      });
    }
  }, 1000);

  /**
   * 清空输入框，并移除地图上的搜索结果(marker)
   */
  function handleClearInput() {
    searchKeyRef.value = "";
    poiList.pois = [];
    amapRef.value?.removeSearchMarker();
  }

  return {
    handleSearch,
    searchKeyRef,
    handleClearInput,
    popupFlexShowRef,
  };
}
